import pymysql


class DBUtil:
    # 定义类属性
    conn = None

    # 创建数据库连接的方法
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                                   database="ihrm", charset="utf8")
        return cls.conn

    # 关闭数据库连接的方法
    @classmethod
    def __close_db(cls):
        cls.conn.close()

    # 数据库的查询方法
    @classmethod
    def query_db(cls, sql):
        cursor = None
        result = None
        try:
            # 创建数据库连接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql,返回查询结果
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as err:
            print("读取数据库报错:", str(err))
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_db()
            return result

    # 数据库的增删改方法
    @classmethod
    def uid_db(cls, sql):
        cursor = None
        try:
            # 创建数据库连接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql,打印一下影响数据库的行数
            cursor.execute(sql)
            affect_rows = cls.conn.affected_rows()
            print("影响数据库的行数=", affect_rows)
            # 事务的提交、回滚
            cls.conn.commit()
        except Exception as err:
            print("增删改操作数据库时出错:", str(err))
            # 事务的回滚
            cls.conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_db()

    pass


if __name__ == '__main__':
    query_sql = "SELECT * from t_book ;"
    res = DBUtil.query_db(query_sql)
    print(res)

    update_sql ="UPDATE t_book set title='三国志' WHERE id =1;"
    DBUtil.uid_db(update_sql)

